package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.dtos.WmNewsStatusDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmNewsMessageConstants;
import com.heima.utils.threadUtil.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.KafkaClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsStatusDto dto) {
        //1.非空判断
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章是否存在
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }
        //4.修改状态
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable())
                    .eq(WmNews::getId, wmNews.getId()));
        }
        //5.向app端发送信息，修改文章上下架
        if (wmNews.getContent() != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.非空判断
        if (dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getType() == -1) {
            dto.setType(null);
        }
        //2.拷贝属性，dto 到 news
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //3.图片转换集合
        List<String> images = dto.getImages();
        if (images != null && images.size() > 0) {
            String imgStr = StringUtils.join(images, ",");
            wmNews.setImages(imgStr);
        }
        //4.第一个抽取方法，保存或者修改news
        saveorUpdateNews(wmNews);
        //5.判断状态，若为草稿则返回
        if (dto.getStatus() == 0) {
            return ResponseResult.okResult(null);
        }
        //6.操作news与material关联的中间表wm_news_material
        //6.1 第二个抽取方法，得到news内容中的图片
        List imageList = getImageList(wmNews);
        //6.2 第三个抽取方法，内容图片添加到wm_news_material（内容图片类型为0）
        contentImageToNews(wmNews, imageList, (short) 0);
        //6.3 第四个抽取方法，封面图片wm_news_material（封面图片类型为1）
        coverImageToNews(wmNews, dto, imageList, (short) 1);

        //审核文章
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 封面图片wm_news_material（封面图片类型为1）
     *
     * @param wmNews
     * @param type
     */
    private void coverImageToNews(WmNews wmNews, WmNewsDto dto, List imageList, short type) {
        //1.获取封面图片
        List<String> images = dto.getImages();

        //2.判断类型为null 自动
        if (dto.getType() == null) {
            //2.1 若是1个或两个图，则取出第一张图片作为封面
            if (imageList.size() >= 1 && imageList.size() < 3) {
                images = (List<String>) imageList.stream().limit(1).collect(Collectors.toList());
                //单图设置类型
                wmNews.setType((short) 1);
            }//2.2 若是3个图及以上，则取出前三张图片作为封面
            else if (imageList.size() >= 3) {
                images = (List<String>) imageList.stream().limit(3).collect(Collectors.toList());
                //多图设置类型
                wmNews.setType((short) 3);
            } else {
                //2.3无图
                wmNews.setType((short) 0);
            }
            wmNews.setImages(StringUtils.join(images, ","));
            updateById(wmNews);
        }
        //新增wm_news_material
        saveNewsMaterial(wmNews, type, images);
    }

    /**
     * 第五个抽取方法
     *
     * @param wmNews
     * @param type
     * @param images
     */
    private void saveNewsMaterial(WmNews wmNews, short type, List<String> images) {
        //1.判断imageList是否有值
        if (images != null && images.size() > 0) {
            //1.1根据地址集合去查询material
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
            //1.2从material抽取出相对应的id集合
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            wmNewsMaterialMapper.saveRelations(materialIds, wmNews.getId(), type);
        }
    }

    /**
     * 第三个抽取方法，内容图片添加到wm_news_material
     *
     * @param wmNews    文章实体
     * @param imageList 内容中抽取的图片集合,图片地址集合
     * @param type      引用类型，0表示内容引用 1表示封面引用
     */
    private void contentImageToNews(WmNews wmNews, List imageList, Short type) {

        saveNewsMaterial(wmNews, type, imageList);
    }

    /**
     * 第二个抽取方法，得到news内容中的图片
     *
     * @param wmNews
     * @return
     */
    private List getImageList(WmNews wmNews) {

        List imageList = new ArrayList();

        //1.获取内容
        String content = wmNews.getContent();
        //2.转化list类型
        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if (map.get("type").equals("image")) {
                String value = (String) map.get("value");
                imageList.add(value);
            }
        }
        return imageList;

    }

    /**
     * 第一个抽取方法，保存或者修改news
     *
     * @param wmNews
     */
    private void saveorUpdateNews(WmNews wmNews) {
        //1补全属性
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        //2.判断news id 若在 先删除中间表，后修改news
        if (wmNews.getId() != null) {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        } else {
            //2.1 不在新增
            save(wmNews);
        }

    }

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //时间范围查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }


        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());

        //发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = page(page, lambdaQueryWrapper);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

}


